import {AfterViewInit, Component, EventEmitter, OnDestroy, OnInit, Output, ViewChild} from '@angular/core';
import {Message} from '../../../../../../ng-tools/src/message/message';
import {AlertComponent, AlertOptions, DynamicComponent, DynamicComponentEvent} from '../../../../../../ng-tools';
import {Subscription} from 'rxjs';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {TicketService} from '../../../../../services/api/ticket.service';
import {HttpParams} from '@angular/common/http';

@Component({
  selector: 'user-service',
  templateUrl: './user-service.component.html',
  styleUrls: ['./user-service.component.scss']
})
export class UserServiceComponent implements OnInit, AfterViewInit, OnDestroy, Message, DynamicComponent {
    context: any;
    currentUserServices;
    dynamic: true;
    events: DynamicComponentEvent;
    subscriptions: Subscription;
  @ViewChild('alert') alert: AlertComponent;
  alertOptions: AlertOptions = {
    theme: 'danger',
    data: null,
    position: 'center'
  };
    @Output() success = new EventEmitter();
    set data(value: any) {
      this.currentUserServices = value;
    }
    userServiceForm: FormGroup;
    allUsers = [];
  constructor(private formBuilder: FormBuilder,
              private ticketService: TicketService) {
      this.userServiceForm = this.formBuilder.group({
          userId: ['', Validators.required],
      });
      // this.userServiceForm.patchValue(this.currentUserServices);
  }
    trigger(eventName: string, ...args) {
        this[eventName].emit(...args);
        if (eventName in this.events) {
            this.events[eventName](...args);
        }
    }
  ngOnInit() {
  }

    save() {
        if (this.userServiceForm.valid) {
            this.ticketService.post(this.ticketService.urls.addCus, this.userServiceForm.value, {
              observe: 'response',
              params: new HttpParams().append('web_token', localStorage.getItem('token'))}).subscribe((resp) => {
              if (resp.body.success) {
                this.trigger('success', this.userServiceForm.value);
              } else {
                this.alertOptions.data = resp.body.msg;
                this.alert.show(this.alertOptions, 2000);
              }
            });
        }
    }
    ngAfterViewInit(): void {
    }

    ngOnDestroy(): void {
    }

}
